package com.cloud.bc.util;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cloud.bc.model.entity.BcConfigs;
import com.cloud.bc.model.entity.BcEmailTemplates;
import com.cloud.bc.model.entity.BcMessageSendRecord;
import com.cloud.bc.model.entity.BcSmsTemplates;
import com.cloud.bc.service.BcConfigsService;
import com.cloud.bc.service.BcEmailTemplatesService;
import com.cloud.bc.service.BcMessageSendRecordService;
import com.cloud.bc.service.BcSmsTemplatesService;
import com.cloud.common.model.enums.MailTemplatesEnum;
import com.cloud.common.model.enums.MessageTypeEnum;
import com.cloud.common.model.enums.SmsTemplatesEnum;
import com.cloud.common.model.request.EmailConfig;
import com.cloud.common.model.request.SmsConfig;
import com.cloud.common.util.EmailUtil;
import com.cloud.common.util.SmsUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@AllArgsConstructor
@Service
public class BcSmsUtil {
    private final SmsUtil smsUtil;
    private final BcSmsTemplatesService bcSmsTemplatesService;
    private final BcConfigsService bcConfigsService;
    private final BcMessageSendRecordService bcMessageSendRecordService;

    /**
     * 发送手机短信
     */
    public boolean sendSms(SmsTemplatesEnum smsTemplatesEnum,
                           String toMobile, JSONObject toValue) {
        //加载邮件模板
        List<BcSmsTemplates> bcEmailTemplates = bcSmsTemplatesService.selectAllCache();
        String bcEmailTemplateStr = JSONUtil.toJsonStr(bcEmailTemplates);
        //加载邮件配置
        List<BcConfigs> bcConfigs = bcConfigsService.selectCacheAll();
        BcConfigs smsConfigModel = bcConfigs.stream().filter(t -> t.getName().equals("SmsConfig")).findFirst().orElse(new BcConfigs());
        SmsConfig smsConfig = JSONUtil.toBean(smsConfigModel.getValue(), SmsConfig.class);

        boolean b = smsUtil.sendSms(smsConfig, bcEmailTemplateStr, smsTemplatesEnum, toMobile, toValue);

        //保存发送记录
        BcMessageSendRecord bcMessageSendRecord = new BcMessageSendRecord();
        bcMessageSendRecord.setSendContent(smsConfig.getSendContent());
        bcMessageSendRecord.setSendType(MessageTypeEnum.MOBILE.getCode());
        bcMessageSendRecord.setSendNo(toMobile);
        bcMessageSendRecordService.save(bcMessageSendRecord);
        return b;
    }
}
